<?php
/*   
编辑者:写php的黄瓜兄
创建日期:2019.4.22
创建控制器/方法:提现
*/

namespace app\inter\controller;
use think\Config;
use  think\Controller;
use think\Db;
use think\Validate;

class Check extends Controller
{

   public function paperList(){
      $param = $this->request->param();
      $where = '1=1';
      if(!empty($param['state'])) $where .= " and a.state={$param['state']}";
      if(!empty($param['keyword'])) $where .= ' and b.title like "%' . $param['keyword'] . '%"';
      $sql = "SELECT a.*,b.title,c.class_name,b.start_date,b.subject_id FROM `exam_plan_class` as a
LEFT JOIN exam_plan as b ON b.id=a.exam_plan_id
LEFT JOIN app_class AS c ON c.class_id=a.class_id WHERE ";
      if($where) $sql .= $where;
      $total_num =  count(Db::query($sql));

      $subject_arr = Config::get('subject');
      $page = isset($param['page'])?$param['page']:1;
      $num = Config::get('page_count');
      $s_page = ($page-1)*$num;
      $e_page = $page*$num;
      $sql .= " LIMIT {$s_page},{$e_page} ";
      $list = Db::query($sql);


      foreach($list as &$item){
         $class_count = Db::table('rel_class_user')->where([
             'class_id' => $item['class_id']
         ])->count();
         $item['class_count'] = $class_count;
         $count = Db::table('exam_plan_student')->where([
            'exam_plan_id' => $item['exam_plan_id'],
            'class_id' => $item['class_id'],
            'state' => 2
         ])->count();
         $item['complete_count'] = $count;
         $item['no_complete_count'] = $class_count-$count;
         $item['rate'] = number_format($count/$class_count, 2)*100 ."%";
         $date = date('m-d');
         $now_y = date('Y');
         if($date<='09-01'){
            $y = $now_y-1;
            $item['class_xq'] = $y . "-" . $now_y ."学年下学期";
         }else{
            $y = $now_y+1;
            $item['class_xq'] = $now_y . "-" . $y ."学年上学期";
         }
         $item['subject_label'] = $subject_arr[$item['subject_id']];
      }

      foreach($list as &$item){
         $ret = Db::table('exam_plan')->where(['id' => $item['exam_plan_id']])->find();
         $ret1 = Db::table('collect')->where(['test_paper_id' => $ret['test_paper_id'], 'uid' => $param['crt_user']])
             ->find();
         $item['is_collect'] = $ret1?1:0;
         $item['is_help'] = $ret['is_help'];
         $item['test_paper_id'] = $ret['test_paper_id'];
      }
      return json(['page_num' => ceil($total_num/Config::get('page_count')),'data' => $list, 'msg' => 'success', 'state' => 10000]);
   }

  //获取学生信息
   public function getStudentInfo(){
      $param = $this->request->param();
      if(empty($param['exam_plan_id'])
      ||empty($param['class_id'])
      ||empty($param['page'])
      )
         return json(['msg' => '参数不全1', 'state' => 10001]);


      //学生得分处理
      if(isset($param['student_id'])){
         $topic_complete_data = Db::table('topic_complete')
             ->where([
                 'exam_plan_id' => $param['exam_plan_id'],
                 'class_id' => $param['class_id'],
                 'student_id' => $param['student_id']
             ])
             ->count();
         $correct_data = Db::table('correct')
             ->field('sum(score) as score_total, count(*) as total')
             ->where([
                 'exam_plan_id' => $param['exam_plan_id'],
                 'class_id' => $param['class_id'],
                 'student_id' => $param['student_id']
             ])
             ->find();
         if($topic_complete_data == $correct_data['total']){
            Db::table('exam_plan_student')->where([
                'student_id' => $param['student_id'],
                'exam_plan_id' => $param['exam_plan_id'],
                'class_id' => $param['class_id'],
            ])->update([
                'score' => $correct_data['score_total'],
                'state' => 2
            ]);
         }else{
            Db::table('exam_plan_student')->where([
                'student_id' => $param['student_id'],
                'exam_plan_id' => $param['exam_plan_id'],
                'class_id' => $param['class_id'],
            ])->update(['score' => $correct_data['score_total']]);
         }
      }



      //exam_plan_id
      $student_data = Db::table('exam_plan_student')->where([
         'exam_plan_id' => $param['exam_plan_id'],
         'class_id' => $param['class_id'],
         'state' => 1,
      ])->find();

      //统计已批改的数量
      $student_data_success = Db::table('exam_plan_student')->where([
          'exam_plan_id' => $param['exam_plan_id'],
          'class_id' => $param['class_id'],
          'state' => 2,
      ])->count();

      //总数
      $num = Db::table('app_class')
          ->where([
              'class_id' => $param['class_id'],
          ])
          ->count();

      $going_num = Db::table('exam_plan_student')->where([
          'exam_plan_id' => $param['exam_plan_id'],
          'class_id' => $param['class_id'],
          'state' => 1,
      ])->count();


      if($student_data){
         $start = $param['page']-1;
         $end = $param['page']+1;
         $sql ="SELECT b.class_name, a.student_id, c.nick FROM `exam_plan_student` as a
LEFT JOIN app_class AS b on b.class_id=a.class_id
LEFT JOIN app_student AS c ON c.user_id=a.student_id
WHERE a.exam_plan_id={$student_data['exam_plan_id']} LIMIT {$start},{$end}";
         $data = Db::query($sql);
         return json([
             'data' => $data[0],
             'success_num'=> $student_data_success,
             'going_num'=> $going_num,
             'num'=> $num,
             'msg' => 'success', 'state' => 10000
         ]);
      }else{
         return json([
             'msg' => '已全部批改完成',
             'success_num'=> $student_data_success,
             'going_num'=> $going_num,
             'num'=> $num,
             'state' => 10002]);
      }
   }

   //获取题目列表
   public function getTopicList(){
      $param = $this->request->param();
      if(!isset($param['exam_plan_id']))  return json(['msg' => '参数不全', 'state' => 10001]);
      $sql = "SELECT a.id,a.pid,a.type FROM `topic` AS a
LEFT JOIN test_paper_topic as b ON b.topic_id=a.id
LEFT JOIN test_paper AS c ON c.id=b.test_paper_id
LEFT JOIN exam_plan as d ON d.test_paper_id=c.id
WHERE d.id={$param['exam_plan_id']}  ORDER BY a.id ASC;";
      $list  = Db::query($sql);
      $k = 1;
      $data = [];
      foreach($list as &$item){
         $ret = Db::table('topic')->where(['pid' => $item['id']])->find();
         if(!$ret) $data[] = [
            'id' => $item['id'],
         ];
      }
      foreach($data as &$item){
         $item['name'] = "第{$k}题";
         $k++;
      }
      return json(['data' => $data, 'msg' => 'success', 'state' => 10000]);
   }

   //获取题目信息
   public function getTopicInfor(){
      $param = $this->request->param();
      if(!isset($param['topic_id']))  return json(['msg' => '参数不全', 'state' => 10001]);
      if(!isset($param['test_paper_id']))  return json(['msg' => '参数不全', 'state' => 10001]);
      $topic_data = Db::table('topic')->field('id,content,analysis,answer')
          ->where(['id' => $param['topic_id']])->find();
      if($topic_data){
         $topic_data['content'] = json_decode($topic_data['content'], true);
         $topic_data['analysis'] = json_decode($topic_data['analysis'], true);
         $topic_data['answer'] = json_decode($topic_data['answer'], true);
         $topic_branch_data = Db::table('topic_branch')
             ->where(['topic_id'  => $param['topic_id']])->select();
         if($topic_branch_data){
            $topic_data['branch_list'] = array_column($topic_branch_data, 'brch_content');
         }
         $ret = Db::table('test_paper_topic')->where(['topic_id' => $param['topic_id'],'test_paper_id' => $param['test_paper_id']])
             ->find();
         $topic_data['score'] = $ret['score'];
         return json(['data' => $topic_data, 'msg' => 'success', 'state' => 10000]);
      }else{
         return json(['msg' => '未查询到信息', 'state' => 10001]);
      }
   }

   //获取学生答案信息
   public function getStudentTopic(){
      $param = $this->request->param();
      if(!isset($param['student_id'])
          ||!isset($param['topic_id'])
          ||!isset($param['exam_plan_id']))
         return json(['msg' => '参数不全', 'state' => 10001]);
      $topic_data = Db::table('topic_complete')->field('id, answer')
          ->where([
          'topic_id' => $param['topic_id'],
          'student_id' => $param['student_id'],
          'exam_plan_id' => $param['exam_plan_id'],
      ])->find();
     
    
   
      if($topic_data){
        
        
          $score = Db::table('correct')->field('score')
          ->where([
          'topic_complete_id' => $topic_data['id'],
          'student_id' => $param['student_id'],
          'exam_plan_id' => $param['exam_plan_id'],
      ])->find();
    
     if($score){
       $topic_data['score']=$score['score'];
     
     }
         return json(['data' => $topic_data, 'msg' => 'success', 'state' => 10000]);
      }else{
         return json(['msg' => '查询失败', 'state' => 10001]);
      }


   }

   //提交得分
   public function submit(){
      $param = $this->request->param();
      if(!isset($param['topic_complete_id'])
          ||!isset($param['postil'])
          ||!isset($param['score'])
          ||!isset($param['crt_user'])
        
        ){
        return json(['msg' => '参数不全', 'state' => 10001]);
      }


      if (!empty($param['imgData'])) {
         $ret = self::base64_image_content($param['imgData'], UPLOAD_FILE_PATH);
         Db::table('topic_complete')->where([
             'id' => $param['topic_complete_id']
         ])->update(['answer' => $ret]);

      }
        
      $ret =Db::table('correct')->where(['topic_complete_id' => $param['topic_complete_id']])->find();
      $com_data = Db::table('topic_complete')->where(['id' => $param['topic_complete_id']])->find();
      if($ret) return json(['msg' => '此题目已经批改', 'state' => 10001]);
      $insert_data = [
         'topic_complete_id' => $param['topic_complete_id'],
         'postil' => $param['postil'],
         'score' => $param['score'],
         'crt_time' => time(),
         'crt_user' => $param['crt_user'],
        
         'student_id' => $com_data['student_id'],
         'exam_plan_id' => $com_data['exam_plan_id'],
         'class_id' => $com_data['class_id'],
      ];
      $update = Db::table('correct')->insert($insert_data, false, true);
      if($update){

         //统计已批改的数量
         $student_data_success = Db::table('exam_plan_student')->where([
             'exam_plan_id' => $com_data['exam_plan_id'],
             'class_id' => $com_data['class_id'],
             'state' => 2,
         ])->count();

         //总数
         $num = Db::table('app_class')
             ->where([
                 'class_id' => $com_data['class_id'],
             ])
             ->count();

         $going_num = Db::table('exam_plan_student')->where([
             'exam_plan_id' => $com_data['exam_plan_id'],
             'class_id' => $com_data['class_id'],
             'state' => 1,
         ])->count();

         return json([
             'data' => '',
             'msg' => 'success',
             'success_num'=> $student_data_success,
             'going_num'=> $going_num,
             'num'=> $num,
             'state' => 10000]);
      }else{
         return json(['msg' => '查询失败', 'state' => 10001]);
      }

   }

   /* base64格式编码转换为图片并保存对应文件夹 */
   public function base64_image_content($base64_image_content,$path){
      //  $base_img是获取到前端传递的src里面的值，也就是我们的数据流文件
      $base_img = str_replace('data:image/octet-stream;base64,', '', $base64_image_content);
//  设置文件路径和文件前缀名称
      $prefix='nx_';
      $output_file = $prefix.time().rand(100,999).'.jpg';
      $path = $path.$output_file;
//  创建将数据流文件写入我们创建的文件内容中
      $ifp = fopen( $path, "wb" );
      fwrite( $ifp, base64_decode( $base_img) );
      fclose( $ifp );
// 第二种方式
// file_put_contents($path, base64_decode($base_img));
// 输出文件
      return '/uploads/'.$output_file;
      if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
         $type = $result[2];
         $new_file = $path."/".date('Ymd',time())."/";
         if(!file_exists($new_file)){
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($new_file, 0700);
         }
         $new_file = $new_file.time().".{$type}";
         if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
            return '/'.$new_file;
         }else{
            return 111;
         }
      }else{
         return 222;
      }

   }

   public function getExamPaperInfor(){
      $param = $this->request->param();
      if(!isset($param['exam_plan_id'])
          ||!isset($param['class_id']))
         return json(['msg' => '参数不全', 'state' => 10001]);
      $class_list = Db::table('rel_class_user')->where(['class_id' => $param['class_id']])->count();
      $student_test = Db::table('exam_plan_student')->where([
          'class_id' => $param['class_id'],
          'exam_plan_id' => $param['exam_plan_id'],
      ])->count();
      $data = [
         'total' => $class_list,
         'completed_total' => $student_test,
         'complete_total' => $class_list-$student_test,
      ];
      return json(['data' => $data, 'msg' => 'success', 'state' => 10000]);
   }

   public function submitAll(){
      $param = $this->request->param();
      if(!isset($param['student_id'])
          ||!isset($param['exam_plan_id'])
          ||!isset($param['class_id'])
          ||!isset($param['crt_user']))
         return json(['msg' => '参数不全', 'state' => -1]);
      $sql = "SELECT sum(b.score) as score_total FROM `topic_complete` as a
LEFT JOIN correct as b ON b.topic_complete_id=a.id
WHERE a.student_id={$param['student_id']} and a.exam_plan_id={$param['exam_plan_id']} AND a.class_id='{$param['class_id']}';";
      $result = Db::query($sql);
      $ret1 = Db::table('exam_plan_student')->where([
          'student_id' => $param['student_id'],
          'exam_plan_id' => $param['exam_plan_id'],
          'class_id' => $param['class_id'],
      ])->update(['score' => $result[0]['score_total']]);
      return json(['data' => '', 'msg' => 'success', 'state' => 10000]);

   }
}